<template>
  <div
    class="draggable"
    :style="style"
    @mousedown="startDrag"
    @mousemove="move"
    @mouseup="stopDrag"
    @mouseleave="stopDrag"
  >
    <div class="cen">ppp</div>
  </div>
</template>

<script setup>
/* eslint-disable */
import { computed, reactive, onMounted, onUnmounted } from "vue";
import { useStore } from "vuex";

const store = useStore();
const search = computed(() => store.getters["getsearch"]);

const state = reactive({
  dragging: false,
  startX: 0,
  startY: 0,
  startBottom: 0,
  startRight: 0,
});

const style = reactive({
  bottom: "150px",
  right: "80px",
  position: "fixed",
  zIndex: 9999,
});

const startDrag = (e) => {
  const { clientX: startX, clientY: startY } = e;
  state.startX = startX;
  state.startY = startY;
  state.startBottom = parseFloat(style.bottom);
  state.startRight = parseFloat(style.right);
  state.dragging = true;
};

const move = (e) => {
  if (!state.dragging) return;

  const { clientX: curX, clientY: curY } = e;
  const { innerHeight: windowHeight, innerWidth: windowWidth } = window;

  const bottom = state.startY - curY + state.startBottom;
  const right = state.startX - curX + state.startRight;

  style.bottom = `${Math.max(0, Math.min(bottom, windowHeight))}px`;
  style.right = `${Math.max(0, Math.min(right, windowWidth))}px`;
};

const stopDrag = () => {
  state.dragging = false;
};

onMounted(() => {
  window.addEventListener("mousemove", move);
  window.addEventListener("mouseup", stopDrag);
});

onUnmounted(() => {
  window.removeEventListener("mousemove", move);
  window.removeEventListener("mouseup", stopDrag);
});
</script>

<style scoped>
.draggable {
  width: 200px;
  height: 200px;
  background-color: rgb(112, 112, 112);
  border: 1px red solid;
  cursor: move;
  pointer-events: none;
}

.cen {
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 18px;
}
</style>
